﻿using FTBS.Models.BLO;
using FTBS.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PagedList;


namespace FTBS.Controllers
{
    public class RoomController : Controller
    {
        private ChairBLO _bloChair = new ChairBLO();
        private RoomBLO _bloRoom = new RoomBLO();
        private TheaterBLO _bloTheater = new TheaterBLO();
        private ChairTypeBLO _bloChairType = new ChairTypeBLO();

        public ActionResult Index(string sortOrder, string currentFilter, string searchString, int? page, bool? isSortDescending)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            List<Room> listRoom = new List<Room>();
            listRoom = _bloRoom.GetListRoom().ToList();
            ViewBag.NameSortParm = "theater_desc";
            ViewBag.CurrentSort = sortOrder;

            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewBag.CurrentFilter = searchString;
            ViewBag.IsSortDes = false;

            if (!String.IsNullOrEmpty(searchString))
            {
                listRoom = listRoom.Where(room => room.Theater.TheaterName.ToUpper().Contains(searchString.ToUpper())
                                                  || room.RoomName.ToString().ToUpper().Contains(searchString.ToUpper())).ToList();
            }

            switch (sortOrder)
            {
                case "theater_desc":
                    if (isSortDescending == true)
                    {
                        listRoom = listRoom.OrderByDescending(room => room.Theater.TheaterName).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listRoom = listRoom.OrderBy(room => room.Theater.TheaterName).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                case "room_desc":
                    if (isSortDescending == true)
                    {
                        listRoom = listRoom.OrderByDescending(room => room.RoomName).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listRoom = listRoom.OrderBy(room => room.RoomName).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                default:
                    listRoom = listRoom.OrderBy(room => room.RoomId).ToList();
                    ViewBag.IsSortDes = false;
                    break;
            }

            int pageSize = 4;
            int pageNumber = (page ?? 1);

            return View(listRoom.ToPagedList(pageNumber, pageSize));
        }
        /// <summary>
        /// create a room of a theater
        /// </summary>
        /// <returns></returns>
        /// <author>nguyenht</author>
        public ActionResult Create()
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            ViewBag.TheaterId = new SelectList(_bloTheater.GetAllTheaterInfo(), "TheaterId", "TheaterName");
     
            return View();
        }

        [HttpPost]
        public ActionResult Create(Room room)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            if (ModelState.IsValid)
            {
                if (!_bloRoom.CheckIsExisted(room))
                {
                    ViewBag.TheaterId = null;
                    _bloRoom.CreateRoom(room);
                    var id = room.RoomId;
                    var theaterId = room.TheaterId;
                    this.Session["TheaterId"] = theaterId;
                    return RedirectToAction("CreateChair/" + id);
                }
                TempData["IsExistTheater"] = "Tên phòng đã được tạo. Xin hãy tạo với tên khác!";
                ViewBag.TheaterId = new SelectList(_bloTheater.GetAllTheaterInfo(), "TheaterId", "TheaterName");
                return View();
            }
            ViewBag.TheaterId = new SelectList(_bloTheater.GetAllTheaterInfo(), "TheaterId", "TheaterName");
            return View(room);
        }
        [HttpPost]
        public ActionResult EditName(int id, string roomName) {
            if (!_bloChair.CheckIsTicket(id)) {
            var room = _bloRoom.GetRoomById(id);
            room.RoomName = roomName;
            if (!_bloRoom.CheckIsExisted(room))
            {
                _bloRoom.SaveChange(room);
                return Redirect("/Room");
            }
            TempData["IsSameRoom"] = true;
            return Redirect("/Room");
            }
            TempData["IsTicket"] = true;
            return Redirect ("/Room");
        } 
        public ActionResult CreateChair(int id = 0)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            this.Session["RoomId"] = id;
            ViewBag.ListFrame = _bloRoom.GetFrame(_bloRoom.GetRoomById(id).TheaterId);  
            ViewBag.ChairType = new SelectList(_bloChairType.LoadChairTypes(), "ChairTypeId", "TypeName");
            return View(_bloChair.LoadChairs(id));
        }

        public ActionResult CreateChairs(string listChair, string chairType, string allChairs)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            var id = Convert.ToInt32(this.Session["RoomId"]);
            string[] strListChairType = chairType.Split(' ');
            string[] strListChair = listChair.Split(' ');
            string[] AstrListChair = allChairs.Split(' ');
            Array.Reverse(strListChairType);
            Array.Reverse(strListChair);
            Array.Reverse(AstrListChair);
            _bloChair.AddChairs(strListChair, id, strListChairType, AstrListChair);
            return RedirectToAction("Index");
        }

        public ActionResult EditChairs(string id,string listChair, string chairType)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            string[] strListChairType = chairType.Split(' ');
            string[] strListChair = listChair.Split(' ');
           int idR = Convert.ToInt32(id);
            _bloChair.EditChairs(strListChair, idR, strListChairType);
            return RedirectToAction("Index");
        }

        public ActionResult CreateChairTable(int x, int y)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            var id = Convert.ToInt32(this.Session["RoomId"]);
            ViewBag.Hori = x;
            ViewBag.Veri = y;
            Room room = _bloRoom.GetRoomById(id);
            room.MaxHeight = x;
            room.MaxLength = y;
            _bloRoom.SaveChange(room);
            ViewBag.ChairType = new SelectList(_bloChairType.LoadChairTypes(), "ChairTypeId", "TypeName");

            return PartialView("TableChair");

        }

        public ActionResult Edit(int id = 0)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            //ViewBag.ChairType = new SelectList(_bloChairType.LoadChairTypes(), "ChairTypeId", "TypeName");
            ViewBag.Room = _bloRoom.GetRoomById(id);
            ViewBag.ChairType = _bloChairType.LoadChairTypes();
            ViewBag.formatName = null;
            List<Chair> chair = _bloChair.LoadChairs(id);
            bool checkTicketRoom = _bloChair.CheckIsTicket(id);

            if (chair == null)
            {
                return HttpNotFound();
            }
            if (checkTicketRoom == true)
            {
                TempData["CanNotEdit"] = true;
                return RedirectToAction("Index");
            }
            return View(chair);
        }

        [HttpDelete, ActionName("Delete")]
        public ActionResult Delete(int id = 0)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            if (_bloRoom.IsRoomUsedForSchedule(id))
            {
                TempData["CanNotDelete"] = true;
                return RedirectToAction("Index");
            }
            else
            {
                Room room = _bloRoom.GetRoomById(id);
                if (room == null)
                {
                    return HttpNotFound();
                }
                _bloRoom.DeleteRoom(room);
                return RedirectToAction("Index");
            }
            
        }
    }
}
